﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.ComponentModel;

namespace SalaryChannel.Web
{
    public class Email
    {
        /// <summary>
        /// 发送Email
        /// </summary>
        /// <param name="fromname">发件人姓名</param>
        /// <param name="senderemail">发件人Email</param>
        /// <param name="senderserver">SMTP</param>
        /// <param name="senderuser">发件人用户名</param>
        /// <param name="senderpassword">发件人密码</param>
        /// <param name="emails">收件人，多个收件人用分号隔开；可以添加收件人姓名,如 Marry:Marry@139.com</param>
        /// <param name="subject">主题</param>
        /// <param name="body">内容</param>
        /// <param name="files">附件列表</param>
        /// <param name="encoding">编码</param>
        public static void SendEmail(string fromname,
            string senderemail,
            string senderserver,
            string senderuser,
            string senderpassword,
            string emails,
            string subject,
            string body,
            string[] files,
            [DefaultValue("GB2312")]string encoding)
        {
            using (MailMessage mailmess = new MailMessage())
            {
                Encoding en = null;
                try
                {
                    en = Encoding.GetEncoding(encoding);
                }
                catch
                {
                    en = Encoding.GetEncoding("GB2312");
                }

                mailmess.From = new MailAddress(senderemail, fromname, en);

                mailmess.To.Clear();
                foreach (string destemail in emails.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                {
                    if (destemail.Contains(":"))
                    {
                        string[] mailInfo = destemail.Split(':');
                        mailmess.To.Add(new MailAddress(mailInfo[1].Trim(), mailInfo[0].Trim()));
                    }
                    else
                    {
                        mailmess.To.Add(destemail);
                    }
                }
                mailmess.Subject = subject;
                mailmess.SubjectEncoding = Encoding.GetEncoding(encoding);
                mailmess.Body = body;
                mailmess.BodyEncoding = Encoding.GetEncoding(encoding);
                if (files != null)
                {
                    foreach (string path in files)
                    {
                        if (!string.IsNullOrEmpty(path))
                            mailmess.Attachments.Add(new Attachment(path));
                    }
                }

                SmtpClient client = new SmtpClient(senderserver);

                client.Credentials = new NetworkCredential(senderuser, senderpassword);

                client.Send(mailmess);
            }
        }
    }
}